import { forwardRef, useImperativeHandle, useState } from 'react';

import { useAntdTable } from 'ahooks';
import { Button, DatePicker, Drawer, Form, Input, Space, Table, Tag } from 'antd';
import { Dayjs } from 'dayjs';

import Filter from '@/components/filter';

import { store } from '@/store';

import { TimeSort } from '@/enum';
import { ManageStatusObj } from '@/enum/manage';
import { manageNeedPage } from '@/services/bizApi/jingyingcaigouxuqiubiaojiekou';

/** 该模块增删改查对象 */
export type BizObject = BIZAPI.ManageNeedEntity;

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: (arr: BIZAPI.ManageNeedEntity[]) => void;
};

export type DemandRef = {
  open: (arg: EditOpenBaseArgs & { manageDeptId?: string }) => void;
};

export type EditProps = {};

const Demand: React.ForwardRefRenderFunction<DemandRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  const [args, setArgs] = useState<ArgumentsType<DemandRef['open']>[0]>();
  const [filter] = Filter.useForm();
  const [open, setOpen] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRows, setSelectedRows] = useState<BIZAPI.ManageNeedEntity[]>([]);

  const table = useAntdTable(
    async ({ current, pageSize }, { id, applyTime, ...formData }) => {
      const [applyTimeBegin, applyTimeEnd] = ((applyTime as [Dayjs?, Dayjs?]) || []).map((v) =>
        v?.format('YYYY-MM-DD HH:mm:ss')
      );
      const res = await manageNeedPage({
        ...formData,
        ...id,
        joinStatus: 0,
        status: 3,
        applyTimeBegin,
        applyTimeEnd,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);
        form.resetFields();
        table.search.submit();
      }
    };
  });

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  const onCancel = () => {
    setOpen(false);
    setSelectedRowKeys([]);
    setSelectedRows([]);
  };

  // 仅保存
  const onSave = () => {
    if (selectedRows?.length > 1) {
      store.app?.message.info('只能关联一条采购需求');
      return;
    }
    args?.onSuccess?.(selectedRows || []);
    setOpen(false);
    setSelectedRowKeys([]);
    setSelectedRows([]);
  };

  return (
    <Drawer
      title="采购需求列表"
      extra={
        <Space>
          <Button type="primary" onClick={onSave}>
            保存
          </Button>
          <Button onClick={onCancel}>取消</Button>
        </Space>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      {/* 筛选 */}
      <Filter onFinish={onSearch} form={filter}>
        <Filter.Item name="applyNumber">
          <Input
            style={{
              width: 180
            }}
            placeholder="请输入申请单号"
          />
        </Filter.Item>
        <Filter.Item name="applyDeptName">
          <Input
            style={{
              width: 180
            }}
            placeholder="请输入申请部门"
          />
        </Filter.Item>
        <Filter.Item name="applyUserName">
          <Input
            style={{
              width: 180
            }}
            placeholder="请输入申请人"
          />
        </Filter.Item>
        <Filter.Item name="applyTime">
          <DatePicker.RangePicker showTime placeholder={['申请时间', '申请时间']} />
        </Filter.Item>
        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: '申请单号',
            dataIndex: 'applyNumber'
          },
          {
            title: '申请部门',
            dataIndex: 'applyDeptName'
          },
          {
            title: '申请时间',
            dataIndex: 'applyTime'
          },
          {
            title: '申请人',
            dataIndex: 'applyUserName'
          },
          {
            title: '采购金额',
            dataIndex: 'purchaseAmount'
          },
          {
            title: '状态',
            dataIndex: 'status',
            render: (v) => {
              const obj = ManageStatusObj.get(v);

              if (obj) {
                return <Tag color={obj.color}>{obj.text}</Tag>;
              }

              return emptyText;
            }
          },
          {
            title: '批准日期',
            dataIndex: 'approveTime'
          },
          {
            title: '批准人',
            dataIndex: 'approveUserName'
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        rowSelection={{
          selectedRowKeys,
          onChange: (keys: React.Key[], rows) => {
            setSelectedRowKeys(keys);
            setSelectedRows(rows);
          }
        }}
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}
    </Drawer>
  );
};

export default forwardRef(Demand);
